const baseUrl = "http://121.196.30.213/thunder/prod-api/api/";

// 请求拦截器
const requestInterceptor = (options) => {
  // 可以在这里添加token等公共参数
  const token = uni.getStorageSync('token');
  if (token) {
    options.header = {
      ...options.header,
      'Authorization': `Bearer ${token}`
    };
  }
  return options;
};

// 响应拦截器
const responseInterceptor = (response) => {
	console.log(response)
  // 处理响应数据
  if (response.statusCode === 200) {
    // 根据实际后端接口规范调整
    if (response.data.code === 200) {
      return response.data;
    } else {
      uni.showToast({
        title: response.data.msg || 'request failed',
        icon: 'none'
      });
      return Promise.reject(response.data);
    }
  } else {
    uni.showToast({
      title: `network error: ${response.statusCode}`,
      icon: 'none'
    });
    return Promise.reject(response);
  }
};

// 错误处理
const errorHandler = (error) => {
  uni.hideLoading();
  uni.showToast({
    title: 'Failed to connect to the network',
    icon: 'none'
  });
  return Promise.reject(error);
};

// 核心请求方法
const request = (options) => {
  const config = {
    method: options.method || 'GET',
    data: options.data || {},
    header: {
      'Content-Type': 'application/json'
    },
    ...options,
	url: baseUrl + options.url
  };
	console.log('最终请求URL:', config.url);
  // 应用请求拦截器
  const interceptedConfig = requestInterceptor(config);
  console.log(interceptedConfig)
  // 显示加载中
  if (options.showLoading !== false) {
    uni.showLoading({
      title: 'Loading...',
      mask: true
    });
  }

  return new Promise((resolve, reject) => {
    uni.request({
      ...interceptedConfig,
      success: (response) => {
        uni.hideLoading();
        try {
          const processedData = responseInterceptor(response);
          resolve(processedData);
        } catch (err) {
          reject(err);
        }
      },
      fail: (error) => {
        uni.hideLoading();
        const processedError = errorHandler(error);
        reject(processedError);
      }
    });
  });
};

// 封装常用请求方法
const http = {
  // GET请求
  get(url, data = {}, options = {}) {
    return request({
      url,
      method: 'GET',
      data,
      ...options
    });
  },

  // POST请求
  post(url, data = {}, options = {}) {
    return request({
      url,
      method: 'POST',
      data,
      ...options
    });
  },

  // PUT请求
  put(url, data = {}, options = {}) {
    return request({
      url,
      method: 'PUT',
      data,
      ...options
    });
  },

  // DELETE请求
  delete(url, data = {}, options = {}) {
    return request({
      url,
      method: 'DELETE',
      data,
      ...options
    });
  }
};

export default http; // 确保有这行代码
